package org.metasketch.demo.model.loader;

import java.io.FileReader;
import java.io.FileWriter;

import org.metasketch.demo.model.ActionRule;
import org.metasketch.demo.model.ActorRole;
import org.metasketch.demo.model.CoordinationLink;
import org.metasketch.demo.model.CoordinationStep;
import org.metasketch.demo.model.DEMOModel;
import org.metasketch.demo.model.OrganizationalFunction;
import org.metasketch.demo.model.OrganizationalUnit;
import org.metasketch.demo.model.ProductionStep;
import org.metasketch.demo.model.TransactionKind;
import org.metasketch.demo.model.TransactionStep;
import org.metasketch.model.BaseModel;

import com.thoughtworks.xstream.XStream;

public class DEMOModelFileHandler {

	private static XStream geXStream() {

		XStream xstream = new XStream();
		xstream.autodetectAnnotations(true);

		xstream.processAnnotations(ActionRule.class);
		xstream.processAnnotations(ActorRole.class);
		xstream.processAnnotations(CoordinationLink.class);
		xstream.processAnnotations(CoordinationStep.class);
		xstream.processAnnotations(OrganizationalFunction.class);
		xstream.processAnnotations(OrganizationalUnit.class);
		xstream.processAnnotations(ProductionStep.class);
		xstream.processAnnotations(TransactionKind.class);
		xstream.processAnnotations(TransactionStep.class);

		xstream.processAnnotations(DEMOModel.class);

		return xstream;
	}

	public static DEMOModel read(String path) throws Throwable {

		try {

			XStream xstream = geXStream();

			FileReader reader = new FileReader(path + "\\\\demo-model.xmi");
			DEMOModel model = (DEMOModel) xstream.fromXML(reader);
			reader.close();

			model.compileIndex();

			return model;

		} catch (Throwable t) {
			t.printStackTrace();
		}

		return new DEMOModel();

	}

	public static void write(BaseModel baseModel, String path) throws Throwable {

		XStream xstream = geXStream();

		FileWriter writer = new FileWriter(path + "\\\\demo-model.xmi");
		xstream.toXML(baseModel, writer);
		writer.close();

	}

}
